package tech.lingrui.mnpanonymousservice.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import tech.lingrui.mnpanonymousservice.model.message.RequestMessage;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试ws
 *
 * @author lqs2
 * @date 2018/11/25, Sun
 */
@Component
@ServerEndpoint(value = "/websocket/{sourceUser}")
public class TestWebSocket {

    /**
     * 在线人数
     */
    private static int onlineNumber = 0;

    /**
     * 所有的对象
     */

    private static Map<String, TestWebSocket> clients = new ConcurrentHashMap<>();


    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    /**
     * 用户名
     */
    private String username;

    /**
     * 会话
     */
    private Session session;

    /**
     * 建立连接
     *
     * @param session 会话
     */
    @OnOpen
    public void onOpen(@PathParam("sourceUser") String sourceUser, Session session) {
        addMember();
        clients.put(sourceUser, this);
        this.session = session;
        this.username = sourceUser;
        System.out.println("有新连接加入！ 当前在线人数" + onlineNumber);
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        subMember();
        clients.remove(username);
        System.out.println("有连接关闭！ 当前在线人数" + onlineNumber);
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        try {
            System.out.println(message  + "=-=--=");
            RequestMessage requestMessage = OBJECT_MAPPER.readValue(message, RequestMessage.class);
            System.out.println("来自客户端消息：" + requestMessage.getContent());
            if (requestMessage.getType() == RequestMessage.MSY_TYPE_TO_ONE) {
                sendMessageTo(requestMessage.getContent(), requestMessage.getDestUser());
            } else {
                sendMessageAll(requestMessage.getContent(), requestMessage.getDestUser());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void sendMessageTo(String message, String destUsername) throws IOException {
        for (TestWebSocket item : clients.values()) {
            if (item.username.equals(destUsername)) {
                item.session.getAsyncRemote().sendText(message);
                break;
            }
        }
    }

    public void sendMessageAll(String message, String fromUsername) throws IOException {
        for (TestWebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText("来自【" + fromUsername + "】的消息: " + message);
        }
    }


//    /**
//     * 发送消息
//     *
//     * @param message 消息
//     */
//    public void sendMessage(String message) {
//        try {
//            session.getBasicRemote().sendText(message);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


    private static synchronized void subMember() {
        onlineNumber--;
    }

    private static synchronized void addMember() {
        onlineNumber++;
    }
}
